package platformlog_logic

import (
	"context"
	"fmt"
	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"
	"yunzhan/common/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryComponentInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryComponentInfoLogic 查询组件信息
func NewQueryComponentInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryComponentInfoLogic {
	return &QueryComponentInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryComponentInfoLogic) QueryComponentInfo(req *types.QueryComponentInfoRequest) (resp *types.QueryComponentInfoResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var selectSQL string
	selectSQL = fmt.Sprintf(`
		SELECT cluster_id, component_name, version, node_host, node_ip, component_role, home_path, data_storage_dir, port, status, additional_info
		FROM %s
		WHERE cluster_id = '%s'`, l.svcCtx.Config.SQLite.Tables.ComponentInfo, req.ClusterID)
	if flag {
		selectSQL = fmt.Sprintf(`
		SELECT cluster_id, component_name, version, node_host, node_ip, component_role, home_path, data_storage_dir, port, status, additional_info
		FROM %s
		WHERE cluster_id = '%s'`, l.svcCtx.Config.Mysql.Tables.ComponentInfo, req.ClusterID)
	}

	// 构建查询条件
	var params []interface{}
	if req.ComponentName != "" {
		selectSQL += " AND component_name = ?"
		params = append(params, req.ComponentName)
	}
	if req.NodeHost != "" {
		selectSQL += " AND node_host = ?"
		params = append(params, req.NodeHost)
	}
	if req.NodeIP != "" {
		selectSQL += " AND node_ip = ?"
		params = append(params, req.NodeIP)
	}
	if req.ComponentRole != "" {
		selectSQL += " AND component_role = ?"
		params = append(params, req.ComponentRole)
	}
	if req.Status {
		selectSQL += " AND status = ?"
		params = append(params, req.Status)
	}

	selectSQL += " ORDER BY node_ip ASC"

	var componentInfos []models.ComponentInfo
	err = l.svcCtx.Conn.QueryRows(&componentInfos, selectSQL, params...)
	if err != nil {
		logx.Errorf("failed to query component info: %v", err)
		return nil, err
	}

	return &types.QueryComponentInfoResponse{
		Code:    200,
		Message: "查询组件信息成功",
		Data:    componentInfos,
	}, nil
}
